<template>
  <div class="realtime-table">
    <div class="header">
      <h2>实时数据</h2>
      <div class="controls">
        <el-select v-model="selectedTopic" placeholder="选择通道" @change="handleTopicChange">
          <el-option
            v-for="topic in topics"
            :key="topic.id"
            :label="topic.topic"
            :value="topic.id"
          />
        </el-select>
        <el-button type="primary" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
      >
        <template #default="scope" v-if="column.formatter">
          {{ column.formatter(scope.row[column.prop]) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 状态变量
const loading = ref(false)
const topics = ref([])
const selectedTopic = ref('')
const tableData = ref([])
const columns = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
let refreshInterval = null

// 获取通道列表
const fetchTopics = async () => {
  try {
    const response = await fetch('/api/topics')
    if (!response.ok) {
      throw new Error('获取通道列表失败')
    }
    const result = await response.json()
    topics.value = result.data
  } catch (error) {
    console.error('获取通道列表失败:', error)
    ElMessage.error(error.message)
  }
}

// 获取表格数据
const fetchData = async () => {
  if (!selectedTopic.value) return

  loading.value = true
  try {
    const response = await fetch(`/api/data/${selectedTopic.value}?page=${currentPage.value}&size=${pageSize.value}`)
    if (!response.ok) {
      throw new Error('获取数据失败')
    }
    const result = await response.json()
    
    // 设置表格数据
    tableData.value = result.data.list
    total.value = result.data.total
    
    // 动态设置列
    if (result.data.list.length > 0) {
      columns.value = Object.keys(result.data.list[0]).map(key => ({
        prop: key,
        label: key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' '),
        width: key === 'id' ? 80 : null,
        formatter: key.includes('time') ? (value) => new Date(value).toLocaleString() : null
      }))
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 处理通道变化
const handleTopicChange = () => {
  currentPage.value = 1
  fetchData()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 手动刷新数据
const refreshData = () => {
  fetchData()
}

// 启动自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh()
  refreshInterval = setInterval(() => {
    if (selectedTopic.value) {
      fetchData()
    }
  }, 60000) // 每60秒刷新一次，显著减少API请求频率
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
}

onMounted(() => {
  fetchTopics()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.realtime-table {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  color: #1f2f3d;
}

.controls {
  display: flex;
  gap: 16px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-select) {
  width: 200px;
}
</style>